#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      alexandre
#
# Created:     03/12/2013
# Copyright:   (c) alexandre 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import os, sys, getopt

work_dir = "C:/Users/alexandre/Desktop/TCC/SVM/SVM_Sharp/SVM_Sharp/files/te/"
saida_dir = "saida/"
svmout_fn = work_dir + "out.txt"
teste_fn = work_dir + "830283766_teste.txt"
train_fn = work_dir + "teste2d_treino_1.txt"
#model_fn = 'C:/Users/alexandre/Desktop/TCC/SVM/SVM_Sharp/SVM_Sharp/bin/Release/model.txt'
model_fn = 'C:/Users/alexandre/Desktop/TCC/SVM/SVM_Sharp/SVM_Sharp/bin/Debug/model.txt'

#bounds = [-50, 50, .2, -50, 50, .2]
bounds = [0, 200, 1, 0, 200, 1]
#bounds = [-1000, 1000, 10, -1000, 1000, 10]
boundoffset = [-1, 1, 0, -1, 1, 0]

def generate_teste():
    generated = ""
    x = bounds[0]
    while( x <= bounds[1]):
        y = bounds[3]
        while( y <= bounds[4]):
            generated += "1 1:" + str(x) + " 2:" + str(y) + "\n"
            y += bounds[5]
        x += bounds[2]

    filename = work_dir + str(hash(generated)) + "_teste.txt"
    print filename
    file = open(filename, "w")
    file.write(generated)
    file.close
    teste_fn = filename
    return filename

def read_svmsharp_output(svmout, teste):
    P = {}
    N = {}
    rows = 0

    for out_row in svmout:
        rows += 1
        teste_row = teste.readline()
        while teste_row.lstrip()[0] == "#":
            teste_row = teste.readline()

        teste_row = teste_row[teste_row.find(' ')+1:].rstrip()
        out_value = int(out_row)
        if(out_value != -1):
            p1 = str(teste_row).split(" ")[0].split(":")[1]
            p2 = str(teste_row).split(" ")[1].split(":")[1]
            P[rows] = p1 + " " + p2
        else:
            p1 = str(teste_row).split(" ")[0].split(":")[1]
            p2 = str(teste_row).split(" ")[1].split(":")[1]
            N[rows] = p1 + " " + p2

    return P, N, rows

def read_svmsharp_train(train):
    P = {}
    N = {}
    count = 0

    for train_row in train:
        if train_row.lstrip()[0] == "#":
            continue

        count += 1
        row = train_row.lstrip()
        first_space = row.find(' ')
        label = row[:first_space]
        values = row[first_space+1:].rstrip()
        if(label == "1" or label == "+1"):
            p1 = str(values).split(" ")[0].split(":")[1]
            p2 = str(values).split(" ")[1].split(":")[1]
            P[count] = p1 + " " + p2
        elif(label == "-1"):
            p1 = str(values).split(" ")[0].split(":")[1]
            p2 = str(values).split(" ")[1].split(":")[1]
            N[count] = p1 + " " + p2
        else:
            assert(False)

    return P, N, count

def read_model_file(model_fn):
    title_text = ""
    modelfile = open(model_fn)
    for line in modelfile:
        if line.find("kernel_type") != -1:
            pos = line.find("kernel_type")+len("kernel_type")+1
            title_text += "kernel " + line[pos:-1] + " ["
            continue
        if line.find("scaled") != -1:
            pos = line.find("scaled")+len("scaled")+1
            title_text += " scaled = " + line[pos:-1]
            continue
        if line.find("C_param") != -1:
            pos = line.find("C_param")+len("C_param")+1
            title_text += " C = " + line[pos:-1]
            continue
        if line.find("WP") != -1:
            pos = line.find("WP")+len("WP")+1
            title_text += " WP = " + line[pos:-1]
            continue
        if line.find("WN") != -1:
            pos = line.find("WN")+len("WN")+1
            title_text += " WN = " + line[pos:-1]
            continue
        if line.find("degree") != -1:
            pos = line.find("degree")+len("degree")+1
            title_text += " degree = " + line[pos:-1]
            continue
        if line.find("gamma") != -1:
            pos = line.find("gamma")+len("gamma")+1
            title_text += " gamma = " + line[pos:-1]
            continue
        if line.find("coef0") != -1:
            pos = line.find("coef0")+len("coef0")+1
            title_text += " coef0 = " + line[pos:-1]
            continue
        if line.find("nr_class") != -1:
            title_text += " ]"
            break
    return title_text

def write_scilab_script(P, N, rows):
    SMP = ""
    SMN = ""
    max_row = rows
    for row in xrange(1, max_row+1):
        if(P.has_key(row)):
            SMP += P[row] + "\n"
        if(N.has_key(row)):
            SMN += N[row] + "\n"

    SMP = SMP[:-1]
    SMN = SMN[:-1]

    if(len(SMP) == 0) or (len(SMN) == 0):
        print "Sem classificacao"
        exit()

    hash_string = str(hash(hash(SMP) + hash(SMN)))

    script_out_fn_final = hash_string + "_" + "_data.txt"
    script_out_fn_finalP = work_dir + saida_dir + "P" + script_out_fn_final
    script_out_fn_finalN = work_dir + saida_dir + "N" + script_out_fn_final

    script_outP = file(script_out_fn_finalP, "w")
    script_outP.write(SMP)
    script_outP.close();

    script_outN = file(script_out_fn_finalN, "w")
    script_outN.write(SMN)
    script_outN.close()

    sc = "scf"

    sc += "\n"

    sc += "MP = fscanfMat('" + script_out_fn_finalP + "');"

    sc += "\n"

    sc += "MN = fscanfMat('" + script_out_fn_finalN + "');"

    sc += "\n"

    sc += "b = gca();"
    sc += "\n"
    c = map(lambda x,y: x+y, boundoffset, bounds)
    c = c[:2] + c[3:-1]
    sc += "b.box = 'off'; "
    #sc += "b.x_location = 'origin'; b.y_location = 'origin'; "
    #sc += "b.x_location = b.y_location ; "
    #sc += "b.data_bounds = " + str(c) + ";"
    #sc += "b.data_bounds = [-2, 8, -2, 8]"
    sc += "\n"

    title_text = read_model_file(model_fn)
    sc += 'title("' + title_text + '")'
    sc += "\n"

    sc +=  "plot(MP(:,1), MP(:,2),'x', MN(:,1), MN(:,2),'rx');"
    sc += "\n"

#    sc += 'legend(["+1";"-1"])'
#    sc += "\n"

    file_title_text = title_text.replace(' ','_')
    file_title_text = file_title_text.replace(',','_')
    file_title_text = file_title_text.replace('[','')
    file_title_text = file_title_text.replace(']','')
    file_title_text = file_title_text.replace('=','')
    file_title_text = file_title_text.replace('__','_')
    file_title_text = hash_string + "_" + file_title_text
    file_title_text_fn = work_dir + saida_dir + file_title_text + ".png"

    sc += "xs2png(b.parent,'" + file_title_text_fn + "')"
    sc += "\n"
    sc += "close"
    sc += "\n"

    print sc

    script_out_final_fn = work_dir + saida_dir + file_title_text + ".sci"
    nao_existia = os.path.isfile(script_out_final_fn) == False
    script_out_final = file(script_out_final_fn, "w")
    script_out_final.write(sc)
    script_out_final.close()

    if 1 or nao_existia:
        cmd = "type " + script_out_final_fn.replace("/","\\") + " >> " + work_dir + saida_dir + "all_scilab_scripts.sci"
        print "-"* 60 + "\n" + cmd
        os.system(cmd)

    return script_out_final_fn

def main():
    print 'rodando...'
    testfile = teste_fn
    outfile = svmout_fn
    trainfile = train_fn
    if len(sys.argv) > 0:
        try:
            opts, args = getopt.getopt(sys.argv[1:],"gxt:o:l:",["testfile=","outfile="])
        except getopt.GetoptError:
            print 'gen_svmsharp_plot.py -t <testfile> -o <outfile> [-g[x]]'
            sys.exit(2)

        generate = False
        force_exit = False
        train_mode = False

        for o,a in opts:
            if o in ('-t'):
                testfile = a
            if o in ('-o'):
                outfile = a
            if o in ('-g'):
                generate = True
            if o in ('-x'):
                force_exit = True
            if o in ('-l'):
                train_mode = True
                trainfile = a

        if generate:
            testfile = generate_teste()
            if force_exit:
                exit()

    if(train_mode):
        train = file(trainfile)
        P, N, rows = read_svmsharp_train(train)
    else:
        svmout = file(outfile)
        test = file(testfile)
        P, N, rows = read_svmsharp_output(svmout, test)

    script_filename = write_scilab_script(P, N, rows)

#    sci_cmd = "C:/Program Files (x86)/scilab-5.4.0/bin/wScilex.exe"
#    sci_par = '-X "' + work_dir + script_filename +'"'

#    print 'Running: ' + sci_cmd + sci_par

#    subprocess.call([sci_cmd, sci_par])
    pass

if __name__ == '__main__':
    main()
